from iClouds.allSerializers import *
from .Serializers import *
from .FilterSets import *
from . import tasks as TASKS
import math


# Create your views here.
class HelloWorld(viewsets.ModelViewSet):
    __title__ = "测试接口"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "创建LOL配置基本",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>创建LOL配置基本</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = TestTasksBaseSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # from iClouds.SDKsync import syncRequest

        # 唇动
        # api = syncRequest()
        # res = api.postLipsync(
        #     audio="https://oss.3vppt.com/ppt_media/Fvn2h5W7fj8hZPFR9hLy-Cs8Jzpy&output.wav",
        #     video="https://oss.3vppt.com/ppt_media/Fp8rACYEnLE9eSLXSMi46bIg10JS&video.mp4",
        # )
        # res = api.listLipsync("b1990e38-3330-42ea-9b3e-83dafc5654d5")
        # print(res)

        # soVits
        # from iClouds.SDKsovits import soVitsMainPage

        # API = soVitsMainPage()
        # tts = API.tts(671)
        # print(tts)

        # 测试订阅
        data = serializer.data.copy()
        res = TASKS.AI_Auto_Tasks_Event(**data)
        return Response({"rescode": 200, "resmsg": res})


class AllinpayRobotConfigViewSet(viewsets.ModelViewSet):
    __title__ = "AI声音模型列表"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI声音模型列表",
        "post": "创建AI声音模型",
        "put": "编辑AI声音模型",
        "patch": "编辑AI声音模型",
        "delete": "移除AI声音模型",
    }
    __doc__ = """	
    list:
    <h4>AI声音模型列表</h4>
    retrieve:
    <h4>AI声音模型详情</h4>
    create:
    <h4>创建AI声音模型</h4>
    update:
    <h4>编辑AI声音模型</h4>
    partial_update:
    <h4>编辑AI声音模型</h4>
    delete:
    <h4>移除AI声音模型</h4>"""
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotConfigPostSerializer
    queryset = AllinpayRobotConfig.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    filterset_class = AllinpayRobotConfigFilterSet
    # filterset_fields = ["status", "gender", "language"]
    search_fields = ["name", "refer"]
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = AllinpayRobotConfigSerializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = AllinpayRobotConfigSerializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(status=0, answer=answer)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save(lasttime=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        instance = self.get_object()
        if not instance.answer == answer:
            raise ValidationError("你要删除别人的声音模型吗?")
        # 移除共享声音模型
        AllinpayRobotList.objects.filter(isbot=instance.id).update(isbot=5)
        AllinpayRobotListmyShare.objects.filter(isbot=instance.id).update(isbot=5)
        AllinpayRobotConfigShare.objects.filter(id=instance.id).delete()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayRobotListViewSet(viewsets.ModelViewSet):
    __title__ = "AI好友列表"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI好友列表",
        "post": "创建AI好友",
        "put": "编辑AI好友",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>AI好友列表</h4>
    retrieve:
    <h4>AI好友详情</h4>
    create:
    <h4>创建AI好友</h4>
        share: 是否共享。0不共享,1共享,2密码认证共享,3好友验证共享
    update:
    <h4>编辑AI好友</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotListSerializer
    queryset = AllinpayRobotList.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    filterset_class = AllinpayRobotListFilterSet
    # filterset_fields = ["isbot", "status", "parent", "share", "gender"]
    search_fields = ["nicename", "basename", "birthday", "phone", "email"]
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return AllinpayRobotListSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        # audio = AllinpayRobotConfig(
        #     name="默认角色",
        #     status=0,
        #     bert="chinese-roberta-wwm-ext-large",
        #     language="Chinese",
        #     answer=answer,
        # )
        # audio.save()

        serializer.save(
            status=1,
            create=timezone.now(),
            lasttime=timezone.now(),
            parent=answer,
            isbot=5,
        )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save(lasttime=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        instance = self.get_object()
        if not instance.parent == answer:
            raise ValidationError("你要删除别人的好友吗?")
        self.perform_destroy(instance)
        AllinpayRobotListmyShare.objects.filter(vid=instance.id).delete()
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayRobotTagViewSet(viewsets.ModelViewSet):
    __title__ = "AI爱好标签"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI爱好标签列表",
        "post": "创建AI爱好标签",
        "put": "编辑AI爱好标签",
        "patch": "编辑AI爱好标签",
        "delete": "移除AI爱好标签",
    }
    __doc__ = """	
    list:
    <h4>AI爱好标签列表</h4>
    retrieve:
    <h4>AI爱好标签详情</h4>
    create:
    <h4>创建AI爱好标签</h4>
        parent = /rebot/botList/<id>
    update:
    <h4>编辑AI爱好标签</h4>
    partial_update:
    <h4>编辑AI爱好标签</h4>
    delete:
    <h4>移除AI爱好标签</h4>"""
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotTagSerializer
    queryset = AllinpayRobotTag.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["parent", "lte"]
    # search_fields = ['phone','email']
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return AllinpayRobotTagSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


# 朋友圈
class AllinpayRobotFriendsViewSet(viewsets.ModelViewSet):
    __title__ = "AI好友朋友圈文章"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI好友朋友圈文章列表",
        "post": "创建AI好友朋友圈文章",
        "put": "编辑AI好友朋友圈文章",
        "patch": "编辑AI好友朋友圈文章",
        "delete": "移除AI好友朋友圈文章",
    }
    __doc__ = """	
    list:
    <h4>AI好友朋友圈文章列表</h4>
    retrieve:
    <h4>AI好友朋友圈文章详情</h4>
    create:
    <h4>创建AI好友朋友圈文章</h4>
        answer = /rebot/botList/<id>
    update:
    <h4>编辑AI好友朋友圈文章</h4>
    partial_update:
    <h4>编辑AI好友朋友圈文章</h4>
    delete:
    <h4>移除AI好友朋友圈文章</h4>"""
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotFriendsSerializer
    queryset = AllinpayRobotFriends.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["types", "answer", "status"]
    # search_fields = ['phone','email']
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return AllinpayRobotFriendsSerializer

    def list(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        fff = (
            AllinpayRobotList.objects.filter(parent=answer)
            .exclude(isbot=0)
            .values_list("id", flat=True)
        )
        queryset = self.filter_queryset(
            self.get_queryset().filter(answer__in=list(fff))
        )
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(create=timezone.now(), status=1)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save(lasttime=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayRobotRemarkViewSet(viewsets.ModelViewSet):
    __title__ = "AI好友朋友圈评论"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI好友朋友圈评论列表",
        "post": "创建AI好友朋友圈评论",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除AI好友朋友圈评论",
    }
    __doc__ = """	
    list:
    <h4>AI好友朋友圈评论列表</h4>
    retrieve:
    <h4>AI好友朋友圈评论详情</h4>
    create:
    <h4>创建AI好友朋友圈评论</h4>
        idx = /rebot/Friends/<id>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除AI好友朋友圈评论</h4>"""
    http_method_names = ["get", "post", "delete"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotRemarkSerializer
    queryset = AllinpayRobotRemark.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["idx"]
    # search_fields = ['phone','email']
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return AllinpayRobotRemarkSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(create=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayRobotGoodsViewSet(viewsets.ModelViewSet):
    __title__ = "AI好友朋友圈点赞"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI好友朋友圈点赞列表",
        "post": "创建AI好友朋友圈点赞",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>AI好友朋友圈点赞列表</h4>
    retrieve:
    <h4>AI好友朋友圈点赞详情</h4>
    create:
    <h4>创建AI好友朋友圈点赞</h4>
        idx = /rebot/Friends/<id>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get", "post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotGoodsSerializer
    queryset = AllinpayRobotGoods.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["idx"]
    # search_fields = ['phone','email']
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return AllinpayRobotGoodsSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(create=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayRobotCollectViewSet(viewsets.ModelViewSet):
    __title__ = "AI好友朋友圈收藏"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "创建LOL配置基本",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>AI好友朋友圈收藏列表</h4>
    retrieve:
    <h4>AI好友朋友圈收藏详情</h4>
    create:
    <h4>创建AI好友朋友圈收藏</h4>
        idx = /rebot/Friends/<id>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get", "post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotCollectSerializer
    queryset = AllinpayRobotCollect.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["idx"]
    # search_fields = ['phone','email']
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return AllinpayRobotCollectSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(create=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayRobotRepeatViewSet(viewsets.ModelViewSet):
    __title__ = "AI好友朋友圈转发"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI好友朋友圈转发列表",
        "post": "创建AI好友朋友圈转发",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>AI好友朋友圈转发列表</h4>
    retrieve:
    <h4>AI好友朋友圈转发详情</h4>
    create:
    <h4>创建AI好友朋友圈转发</h4>
        idx = /rebot/Friends/<id>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get", "post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotRepeatSerializer
    queryset = AllinpayRobotRepeat.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["idx"]
    # search_fields = ['phone','email']
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return AllinpayRobotRepeatSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(create=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayRobotBaseViewSet(viewsets.ModelViewSet):
    __title__ = "AI特征训练"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI特征训练列表",
        "post": "创建AI特征训练",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>AI特征训练列表</h4>
    retrieve:
    <h4>AI特征训练详情</h4>
    create:
    <h4>创建AI特征训练</h4>
        answer = /rebot/botList/<id>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get", "post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotBaseSerializer
    queryset = AllinpayRobotBase.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["status", "answer"]
    # search_fields = ['phone','email']
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return AllinpayRobotBaseSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(create=timezone.now(), status=0)
        return Response({"rescode": 200, "resmsg": serializer.data})


# ========================================================================================
# 文本聊闲
# ========================================================================================


class UploadLocalViewSet(viewsets.ModelViewSet):
    __title__ = "音频解析"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "音频解析",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>音频解析</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AudioToTextSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # from rebot.utils import img_proccess_save

        # video = serializer.validated_data["audio"]
        # video_file = "audio"  # 图片存储的文件夹
        # video_name, video_backend_relative_path = img_proccess_save(video, video_file)
        # if serializer.validated_data["audio"] == "":
        #     serializer.validated_data["audio"] = video_name
        # serializer.save(owner=self.request.user, file_path=video_backend_relative_path)
        # print(video_name, video_backend_relative_path)

        res = TASKS.do_AudioForAudio.delay(**serializer.data)
        return Response({"rescode": 200, "resmsg": res.task_id})


class RebotTextPostViewSet(viewsets.ModelViewSet):
    __title__ = "AI文本合成任务"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "AI好友聊天",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>AI好友聊天</h4>
        {
            "user":1,
            "chat" : [
                {"role": "assistant", "content": "You are a helpful assistant."},
                {"role": "user", "content": "如何做西红柿炒鸡蛋？"},
            ] ,
            "cast": "Text | Sound | Video" ,
        } 
        最大列表不超过6 
        
        Sound 模式 返回 GUID , 需要再次轮询结果21接口.
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = RebotChatTextSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.data.copy()

        share = data.get("share", 0)
        if not share:
            try:  # 加载好友信息
                r = AllinpayRobotList.objects.get(id=data.get("user"), isbot__gt=0)
            except BaseException as err:
                raise ValidationError(f"加载私密好友信息失败 {err}")
        else:
            try:
                r = AllinpayRobotListmyShare.objects.get(id=data.get("user"))
            except BaseException as err:
                raise ValidationError(f"加载共享好友信息失败 {err}")

        # 创建任务
        guid = str(uuid.uuid1())
        reqsn = f'VP{time.strftime("%Y%m%d%H%M%S", time.localtime())}{has_chocode(6)}'
        task = AllinpayRobotQiniuLog(
            **{
                "reqsn": reqsn,
                "guid": guid,
                "mode": "Text",
                "answer": answer,
                "model": r.isbot,
                "mate": r.id,
                "matr": share,
                "matter": data.get("chat"),
                "language": "Chinese",
                "status": 0,
                "current": timezone.now(),
                "description": "文本提问",
            }
        )
        task.save()
        try:  # 扣费
            TASKS.task_Consumption(**{"task_id": task.id})
        except BaseException as err:
            raise ValidationError(err)
        # 任务调度
        res = TASKS.tasks_Manager.delay(**{"task_id": task.id})
        # res = TASKS.do_ChatForText.delay(**serializer.data)
        return Response({"rescode": 200, "resmsg": guid, "task": res.task_id})


class RebotAudioPostViewSet(viewsets.ModelViewSet):
    __title__ = "AI音频合成任务"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "创建AI音频合成任务",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>创建AI音频合成任务</h4>
        调用21#接口获取结果
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = RebotAudioPostSerializer
    queryset = None

    def hasFriend(self, fid):
        """查询虚拟好友"""
        try:
            r = AllinpayRobotList.objects.get(id=fid, status=1)
        except BaseException as err:
            return None
        else:
            return r

    def hasModelAI(self, mid):
        """查询AI模型"""
        try:
            r = AllinpayRobotConfig.objects.get(id=mid, status=1)
        except BaseException as err:
            return None
        else:
            return r

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        guid = str(uuid.uuid1())
        data = serializer.data.copy()

        # 判断余额
        args = TASKS.balance_from_userid(answer)
        if args[0] < settings.RPBOT_MONEY_AUDIO:
            raise ValidationError(f"账户余额不足")

        # 创建扣费
        reqsn = f'VP{time.strftime("%Y%m%d%H%M%S", time.localtime())}{has_chocode(6)}'
        sell = TASKS.balance_from_userai("Audio")
        pay = TASKS.User_account_deduction(
            **{
                "reqsn": reqsn,
                "description": sell[1],
                "amoney": sell[0],
                "atotal": 0,
                "userid": answer,
                "dbid": settings.ROBOT_MONEY_DEFAULT,
                "current": timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
            }
        )
        if not pay == "success":
            raise ValidationError(f"支付失败")

        # 创建任务
        Friend = self.hasFriend(data["user"])
        if not Friend:
            raise ValidationError("虚拟好友错误")
        Models = self.hasModelAI(Friend.isbot)
        if not Models:
            raise ValidationError("AI模型不可用")
        szer = AllinpayRobotQiniuLogSerializer(
            data={
                "chat": data["chat"],
                "guid": guid,
                "language": "Chinese",
                "answer": answer,
                "mode": "Audio",
                "reqsn": reqsn,
                "amoney": sell[0],
                "model": Models.id,
                "mate": Friend.id,
            }
        )
        szer.save()

        # 云任务
        r = TASKS.MakeSoundTasks.delay(**{"task_id": szer.data["id"]})
        # 任务缓存
        # rds = TASKS.get_redis_connection("sysconf")
        # rds.rpush(
        #     "audio",
        #     szer.data["id"],
        # )
        # count = rds.llen("audio")

        return Response(
            {
                "rescode": 200,
                "resmsg": guid,
                "count": 0,
                "content": data["chat"],
            }
        )


class RebotVideoPostViewSet(viewsets.ModelViewSet):
    __title__ = "AI视频合成任务"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "创建AI视频合成任务",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>创建AI视频合成任务</h4>
        调用21#接口获取结果
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = RebotVideoPostSerializer
    queryset = None

    def hasFriend(self, fid):
        """查询虚拟好友"""
        try:
            r = AllinpayRobotList.objects.get(id=fid, status=1)
        except BaseException as err:
            return None
        else:
            return r

    def hasModelAI(self, mid):
        """查询AI模型"""
        try:
            r = AllinpayRobotConfig.objects.get(id=mid, status=1)
        except BaseException as err:
            return None
        else:
            return r

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        guid = str(uuid.uuid1())
        data = serializer.data.copy()

        # 判断余额
        args = TASKS.balance_from_userid(answer)
        if args[0] < settings.RPBOT_MONEY_VIDEO:
            raise ValidationError("账户余额不足")

        # 创建扣费
        reqsn = f'VP{time.strftime("%Y%m%d%H%M%S", time.localtime())}{has_chocode(6)}'
        sell = TASKS.balance_from_userai("Video")
        pay = TASKS.User_account_deduction(
            **{
                "reqsn": reqsn,
                "description": sell[1],
                "amoney": sell[0],
                "atotal": 0,
                "userid": answer,
                "dbid": settings.ROBOT_MONEY_DEFAULT,
                "current": timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
            }
        )
        if not pay == "success":
            raise ValidationError("支付失败")
        # 创建任务
        Friend = self.hasFriend(data["user"])
        if not Friend:
            raise ValidationError("虚拟好友错误")
        Models = self.hasModelAI(Friend.isbot)
        if not Models:
            raise ValidationError("AI模型不可用")
        szer = AllinpayRobotQiniuLogSerializer(
            data={
                "image": Models.image,
                "audio": data["audio"],
                "guid": guid,
                "answer": answer,
                "mode": "Video",
                "reqsn": reqsn,
                "amoney": sell[0],
                "mate": Friend.id,
                "model": Models.id,
            }
        )
        szer.is_valid(raise_exception=True)
        szer.save()
        # 云任务
        r = TASKS.MakeSoundTasks.delay(**{"task_id": szer.data["id"]})
        # 任务缓存
        # rds = get_redis_connection("sysconf")
        # rds.rpush(
        #     "video",
        #     szer.data["id"],
        # )
        # count = rds.llen("video")
        return Response(
            {
                "rescode": 200,
                "resmsg": guid,
                "count": 0,
                "content": "",
            }
        )


class RebotChatGetViewSet(viewsets.ModelViewSet):
    __title__ = "AI合成任务提取"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "AI合成任务提取",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>AI合成任务提取</h4>
        该接口为临时消息队列，只生存180秒。
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = RebotChatGetSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        rds = TASKS.get_redis_connection("sysconf")
        if not rds.exists(serializer.data["guid"]):
            return Response({"rescode": 400, "resmsg": "未找到数据"})
        return Response({"rescode": 200, "resmsg": rds.get(serializer.data["guid"])})


class RebotChatPostViewSet(viewsets.ModelViewSet):
    __title__ = "AI合成任务提交"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI合成任务",
        "post": "AI合成任务提交",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>提取AI合成任务</h4>
    retrieve:
    <h4>AI合成任务详情</h4>
        禁用
    create:
    <h4>AI合成任务提交</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get", "post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = RebotChatPostSerializer
    queryset = None

    def hasBotConf(self, user):
        """查询AI近照配置"""
        try:
            r = AllinpayRobotList.objects.get(id=user)
            g = AllinpayRobotConfig.objects.get(id=r.isbot)
        except BaseException as err:
            return ""
        else:
            return g.image

    def hasTasksAttr(self, tid):
        """查询任务详情"""
        try:
            r = AllinpayRobotQiniuLog.objects.get(id=tid, status=0)
        except BaseException as err:
            return None
        else:
            return ModelAllinpayRobotQiniuLogSerializer(r).data

    def list(self, request, *args, **kwargs):
        raise MyBaseError("错误的请求")

    def retrieve(self, request, *args, **kwargs):
        if not request.META.get("HTTP_NAME") == "aniPortrait":
            raise NotAuthenticated("身份验证失败")
        # 提取任务
        rds = TASKS.get_redis_connection("sysconf")
        if kwargs.get("pk") == "11":
            res = rds.blpop("audio", 1)
        elif kwargs.get("pk") == "12":
            res = rds.blpop("video", 1)
        elif kwargs.get("pk") == "13":
            res = rds.blpop("lipsync", 1)
        elif kwargs.get("pk") == "14":
            res = rds.blpop("opencv", 1)
        else:
            raise MyBaseError("错误的请求")
        data = self.hasTasksAttr(res[1]) if res else None
        return Response({"rescode": 200, "resmsg": data})

    def create(self, request, *args, **kwargs):
        if not request.META.get("HTTP_NAME") == "aniPortrait":
            raise NotAuthenticated("身份验证失败")
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        # TASKS.logger.info(f'[任务回调] 收到任务回调 {serializer.data}')
        # return Response({"rescode": 200, "resmsg": "success"})

        # 任务对象
        try:
            task = AllinpayRobotQiniuLog.objects.get(guid=serializer.data["guid"])
        except BaseException as err:
            print("err:", err)
            raise ValidationError("任务不存在")

        # 判断任务
        res = serializer.data.copy()
        TASKS.logger.info(f"[任务回调] 收到任务回调 {task.id} {res}")
        rds = get_redis_connection("sysconf")

        if not res.get("code") == 200:
            task.description = res.get("data")
            task.save()
            return Response({"rescode": 200, "resmsg": "success"})

        if res.get("plan") == "Audio":
            if task.mode in ["Audio", "Voice"]:
                task.audio = res.get("data")
                task.status = 1
                task.description = "完成"
                task.lasttime = timezone.now()
                task.save()
                # 设置结果
                rds.set(task.guid, task.audio)
                rds.expire(task.guid, 180)
            if task.mode in [
                "Video",
                "Mpeg",
                "Lipsync",
                "Opencv",
            ]:
                task.audio = res.get("data")
                task.description = "等待"
                task.save()
            if task.mode in ["Video", "Mpeg"]:
                rds.rpush("video", task.id)
            if task.mode == "Lipsync":
                rds.rpush("lipsync", task.id)
            if task.mode == "Opencv":
                rds.rpush("opencv", task.id)
            if task.mode == "Voice":
                TASKS.weChatModelMessages.delay(**{"task": task.id})
        if res.get("plan") == "Video":
            pass
        if res.get("plan") == "Lipsync":
            task.description = res.get("data")
            task.save()
        if res.get("plan") == "Opencv":
            pass
        return Response({"rescode": 200, "resmsg": "success"})


class RobotConfigViewSet(viewsets.ModelViewSet):
    __title__ = "AI声音配置列表"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI配置列表",
        "post": "创建LOL配置基本",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>AI配置列表</h4>
    retrieve:
    <h4>AI配置详情</h4>
    create:
    <h4>创建LOL配置基本</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayRobotConfigPostSerializer
    queryset = AllinpayRobotConfig.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["status", "gender", "language"]
    search_fields = ["name", "refer"]
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return AllinpayRobotConfigPostSerializer

    def list(self, request, *args, **kwargs):
        if not request.META.get("HTTP_NAME") == "aniPortrait":
            raise NotAuthenticated("身份验证失败")
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = AllinpayRobotConfigSerializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        if not request.META.get("HTTP_NAME") == "aniPortrait":
            raise NotAuthenticated("身份验证失败")
        instance = self.get_object()
        serializer = AllinpayRobotConfigSerializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class RobotListViewSet(viewsets.ModelViewSet):
    __title__ = "AI好友列表"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI好友列表",
        "post": "创建AI好友",
        "put": "编辑AI好友",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>AI好友列表</h4>
    retrieve:
    <h4>AI好友详情</h4>
    create:
    <h4>创建AI好友</h4>
    update:
    <h4>编辑AI好友</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayRobotListSerializer
    queryset = AllinpayRobotList.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["isbot", "status", "parent"]
    # search_fields = ['phone','email']
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return AllinpayRobotListSerializer

    def list(self, request, *args, **kwargs):
        if not request.META.get("HTTP_NAME") == "aniPortrait":
            raise NotAuthenticated("身份验证失败")
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        if not request.META.get("HTTP_NAME") == "aniPortrait":
            raise NotAuthenticated("身份验证失败")
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


# ========================================================================================
# 订阅事件
# ========================================================================================
class AllinpayRobotModelsViewSet(viewsets.ModelViewSet):
    __title__ = "AI事件订阅模板"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI事件订阅模板列表",
        "post": "创建AI事件订阅模板",
        "put": "编辑AI事件订阅模板",
        "patch": "编辑AI事件订阅模板",
        "delete": "移除AI事件订阅模板",
    }
    __doc__ = """	
    list:
    <h4>AI事件订阅模板列表</h4>
    retrieve:
    <h4>AI事件订阅模板详情</h4>
    create:
    <h4>创建AI事件订阅模板</h4>
    update:
    <h4>编辑AI事件订阅模板</h4>
    partial_update:
    <h4>编辑AI事件订阅模板</h4>
    delete:
    <h4>移除AI事件订阅模板</h4>"""
    http_method_names = ["get", "post", "put", "delete"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotModelsSerializer
    queryset = AllinpayRobotModels.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    filterset_class = AllinpayRobotModelsFilterSet
    # filterset_fields = ["mode", "answer", "status"]
    search_fields = ["name"]
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # if AllinpayRobotModels.objects.filter(name=serializer.data["name"], answer=answer).count():
        #     raise ValidationError("名称重复")
        serializer.save(answer=answer, status=1, create=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = False
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        instance = self.get_object()
        if not instance.answer == answer:
            raise ValidationError("对象所属错误")
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class PeriodicTaskViewSet(viewsets.ModelViewSet):
    __title__ = "创建订阅AI事件"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询订阅AI事件列表",
        "post": "创建订阅AI事件",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除订阅事件",
    }
    __doc__ = """	
    list:
    <h4>订阅AI事件列表</h4>
    retrieve:
    <h4>订阅AI事件详情</h4>
    create:
    <h4>创建订阅AI事件</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除订阅事件</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = PeriodicTaskSerializer
    queryset = PeriodicTask.objects.all()

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=answer)

        PeriodicTasks.update_changed()
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayRobotQiniuViewSet(viewsets.ModelViewSet):
    __title__ = "历史多媒体任务"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询历史多媒体任务列表",
        "post": "创建LOL配置基本",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>历史多媒体任务列表</h4>
    retrieve:
    <h4>历史多媒体任务详情</h4>
    create:
    <h4>创建LOL配置基本</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotQiniuSerializer
    queryset = AllinpayRobotQiniu.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["uid", "guid", "types"]
    # search_fields = ['phone','email']
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def get_serializer_class(self):
        # if self.request and self.request.version == '1':
        #     return NewStaffUserbaseListSerializer
        return AllinpayRobotQiniuSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


# ===================================================================
# 模板消息测试
# ===================================================================
class weChatModelMessageTestViewSet(viewsets.ModelViewSet):
    __title__ = "模板消息测试"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "创建LOL配置基本",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>模板消息测试</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        res = TASKS.weChatModelMessagesTest.delay(**{"user": answer})
        return Response({"rescode": 200, "resmsg": serializer.data})


# ========================================================
# 支付部分
# ========================================================
class AllinpayRobotMoneyTaocanViewSet(viewsets.ModelViewSet):
    __title__ = "充值套餐"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询充值套餐列表",
        "post": "创建LOL配置基本",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>充值套餐列表</h4>
        "money": 1, # 代币记录ID
        "fund": 1, # 1单位代币
        "amount": 1, # 1分法币
    retrieve:
    <h4>充值套餐详情</h4>
    create:
    <h4>创建LOL配置基本</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayRobotMoneyTaocanSerializer
    queryset = AllinpayRobotMoneyTaocan.objects.filter(
        money=settings.ROBOT_MONEY_DEFAULT
    )

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["status"]
    # search_fields = ["money", "status"]
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayRobotReqsnRefundViewSet(viewsets.ModelViewSet):
    __title__ = "退款充值订单"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "退款充值订单",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>退款充值订单</h4>
        仅支持3天以内的整单退款,同时代币会扣除,若代币不足则为负数.
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [] if settings.DEBUG else [AdminJWTAuthentication]
    permission_classes = [AllPermissions] if settings.DEBUG else [AdminPermissions]
    serializer_class = AllinpayRobotReqsnRefundSerializer
    queryset = AllinpayRobotReqsn.objects.all()

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 2
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        AllinpayRobotReqsnRefund.objects.filter(
            orderno=serializer.data["out_trade_no"]
        ).update(officer=answer, status=1, lasttime=timezone.now())
        res = TASKS.wePaysToweAppsRefund(**serializer.data)
        return Response({"rescode": 200, "resmsg": res})


class AllinpayRobotReqsnCloseViewSet(viewsets.ModelViewSet):
    __title__ = "关闭充值订单"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "关闭充值订单",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>关闭充值订单</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotReqsnCloseSerializer
    queryset = AllinpayRobotReqsn.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        res = TASKS.wePaysToweAppsClose(**serializer.data)
        return Response({"rescode": 200, "resmsg": res})


class AllinpayRobotReqsnPostViewSet(viewsets.ModelViewSet):
    __title__ = "创建充值订单"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "创建充值订单",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>创建充值订单</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotReqsnPostSerializer
    queryset = AllinpayRobotReqsn.objects.all()

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 2
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=answer, creattime=timezone.now())
        res = TASKS.wePaysToweAppsPrepay(**serializer.data)
        return Response({"rescode": 200, "resmsg": res})


class AllinpayRobotReqsnViewSet(viewsets.ModelViewSet):
    __title__ = "查询充值订单"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询充值订单列表",
        "post": "创建LOL配置基本",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>查询充值订单列表</h4>
    retrieve:
    <h4>查询充值订单详情</h4>
    create:
    <h4>创建LOL配置基本</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotReqsnSerializer
    queryset = AllinpayRobotReqsn.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    filterset_class = AllinpayRobotReqsnFilterSet
    # filterset_fields = ["answer","mark","openid"]
    search_fields = ["reqsn", "transaction_id"]
    ordering_fields = ["-id", "id"]

    pagination_class = StandardPagination

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayRobotAccountViewSet(viewsets.ModelViewSet):
    __title__ = "用户账户流水"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询用户账户流水列表",
        "post": "创建LOL配置基本",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>用户账户流水列表</h4>
    retrieve:
    <h4>用户账户流水详情</h4>
    create:
    <h4>创建LOL配置基本</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = ModelAllinpayRobotAccountSerializer
    queryset = AllinpayRobotAccount.objects.all().order_by("-id")

    # filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    # filterset_fields = ['status']
    # search_fields = ['phone','email']
    # ordering_fields = 'id'

    pagination_class = StandardPagination

    def list(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 3
        queryset = self.filter_queryset(self.get_queryset().filter(userid=answer))
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
                "balance": queryset.last().bmoney if c else 0,
                "accumulate": queryset.last().btotal if c else 0,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayUserVerifyViewSet(viewsets.ModelViewSet):
    __title__ = "编辑特权密码"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "编辑特权密码",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>编辑特权密码</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayUserVerifySerializer
    queryset = AllinpayUserVerify.objects.all()

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=answer, lasttime=timezone.now())
        return Response({"rescode": 200, "resmsg": "success"})


class AllinpayRobotReqsndofundViewSet(viewsets.ModelViewSet):
    __title__ = "申请退款"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "申请退款",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>申请退款</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotReqsndofundSerializer
    queryset = AllinpayRobotReqsnRefund.objects.all()

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=answer)
        return Response({"rescode": 200, "resmsg": serializer.data})


# ========================================================================================
# ai模型
class AllinpayRobotListvipViewSet(viewsets.ModelViewSet):
    __title__ = "ai模型充值"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "ai模型充值",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>ai模型充值</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotListvipPostSerializer
    queryset = AllinpayRobotListvip.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 扣费
        sess = {
            "reqsn": serializer.data.get("reqsn"),
            "description": "AI模型续费",
            "amoney": serializer.data.get("amount"),
            "atotal": 0,
            "userid": serializer.data.get("answer"),
            "dbid": settings.ROBOT_MONEY_DEFAULT,
            "current": serializer.data.get("current"),
        }
        res = TASKS.User_account_deduction(**sess)

        return Response({"rescode": 200, "resmsg": res})


class AllinpayRobotConfigShareViewSet(viewsets.ModelViewSet):
    __title__ = "创建模型分享"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询我的共享模型列表",
        "post": "创建我的共享模型",
        "put": "编辑我的共享模型",
        "patch": "编辑LOL配置基本",
        "delete": "移除我的共享模型",
    }
    __doc__ = """	
    list:
    <h4>我的共享模型列表</h4>
    retrieve:
    <h4>我的共享模型详情</h4>
    create:
    <h4>创建我的共享模型</h4>
    update:
    <h4>编辑我的共享模型</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除我的共享模型</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotConfigShareSerializer
    queryset = AllinpayRobotConfigShare.objects.all()

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=answer)
        return Response(
            {
                "rescode": 200,
                "resmsg": "SUCCESS",
                # "resmsg": ModelAllinpayRobotConfigShareSerializer(serializer.data).data,
            }
        )


class myAllinpayRobotConfigShareViewSet(viewsets.ModelViewSet):
    __title__ = "我的分享模型"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询我的共享模型列表",
        "post": "创建我的共享模型",
        "put": "编辑我的共享模型",
        "patch": "编辑LOL配置基本",
        "delete": "移除我的共享模型",
    }
    __doc__ = """	
    list:
    <h4>我的共享模型列表</h4>
    retrieve:
    <h4>我的共享模型详情</h4>
    create:
    <h4>创建我的共享模型</h4>
    update:
    <h4>编辑我的共享模型</h4>
    partial_update:
    <h4>编辑我的共享模型</h4>
        仅提供以下参数:
        audio	:  音频合成价格
        video	:  预留待定
        movie   :  预留待定
    delete:
    <h4>移除我的共享模型</h4>"""
    http_method_names = ["get", "patch", "delete"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = ModelAllinpayRobotConfigShareSerializer
    queryset = AllinpayRobotConfigShare.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["status", "answer"]
    # search_fields = ['phone','email']
    ordering_fields = "id"

    pagination_class = StandardPagination

    def list(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 3
        partial = False
        instance = self.get_object()
        if not instance.answer == answer:
            raise ValidationError("只能编辑自己的共享模型")
        db = dict(request.data).keys()
        if "status" in db:
            raise ValidationError("参数错误: status")
        if "answer" in db:
            raise ValidationError("参数错误: answer")
        if "current" in db:
            raise ValidationError("参数错误: current")
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=answer)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        instance = self.get_object()
        # print(answer, instance.answer)
        if not instance.answer == answer:
            raise ValidationError("只能移除自己的共享模型")
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayRobotConfigSalesViewSet(viewsets.ModelViewSet):
    __title__ = "创建声音模型评分"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI爱好标签列表",
        "post": "创建AI爱好标签",
        "put": "编辑AI爱好标签",
        "patch": "编辑AI爱好标签",
        "delete": "移除AI爱好标签",
    }
    __doc__ = """
    list:
    <h4>AI爱好标签列表</h4>
    retrieve:
    <h4>AI爱好标签详情</h4>
    create:
    <h4>创建声音模型评分</h4>
    update:
    <h4>编辑AI爱好标签</h4>
    partial_update:
    <h4>编辑AI爱好标签</h4>
    delete:
    <h4>移除AI爱好标签</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotConfigSalesSerializer
    queryset = AllinpayRobotQiniuLog.objects.all()

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 验证数据
        reqsn = serializer.data.get("ssid")
        score = serializer.data.get("score")

        # 调取数据
        try:
            r = AllinpayRobotQiniuLog.objects.get(id=reqsn)
        except BaseException as err:
            raise ValidationError("查询消费记录失败")
        else:
            if not r.model:
                raise ValidationError("未找到相关声音模型")
            if not r.answer == answer:
                raise ValidationError("只能本人参与")
        # 检测刷单
        s = AllinpayRobotConfigSales.objects.filter(reqsn=r.reqsn).count()
        if s:
            raise ValidationError("禁止刷单行为")

        # 保存数据
        data = {
            "mid": r.model,
            "scene": r.mode,
            "reqsn": r.reqsn,
            "pay": r.amoney,
            "answer": answer,
            "score": score,
            "current": timezone.now(),
        }
        t = AllinpayRobotConfigSales(**data)
        t.save()
        return Response({"rescode": 200, "resmsg": t.id})


class ModelAllinpayRobotConfigSalesViewSet(viewsets.ModelViewSet):
    __title__ = "ai模型评分"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询声音模型评分列表",
        "post": "创建声音模型评分",
        "put": "ai模型评分",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>查询声音模型评分列表</h4>
    retrieve:
    <h4>声音模型评分详情</h4>
    create:
    <h4>创建LOL配置基本</h4>
    update:
    <h4>ai模型评分</h4>
        {id} 模型租用记录ID
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = [
        "get",
    ]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    # serializer_class = AllinpayRobotConfigSalesSerializer
    serializer_class = ModelAllinpayRobotConfigSalesSerializer
    queryset = AllinpayRobotConfigSales.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["mid", "scene", "answer"]
    search_fields = ["reqsn"]
    ordering_fields = "id"

    pagination_class = StandardPagination

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


# =======================================================================================
# ai模板订阅
class AllinpayRobotModelsShareViewSet(viewsets.ModelViewSet):
    __title__ = "分享模板"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "分享模板",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>分享模板</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotModelsShareSerializer
    queryset = AllinpayRobotModelsShare.objects.all()

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=answer)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayRobotModelsSalesViewSet(viewsets.ModelViewSet):
    __title__ = "订阅模板评分"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询订阅模板评分列表",
        "post": "创建LOL配置基本",
        "put": "订阅模板评分",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>订阅模板评分列表</h4>
    retrieve:
    <h4>订阅模板评分详情</h4>
    create:
    <h4>创建LOL配置基本</h4>
    update:
    <h4>订阅模板评分</h4>
        {id} 订阅模板使用记录ID
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = [
        "post",
    ]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotModelsSalesSerializer
    # serializer_class = ModelAllinpayRobotModelsSalesSerializer
    queryset = AllinpayRobotModelsSales.objects.all()

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        # 验证数据
        reqsn = serializer.data.get("ssid")
        score = serializer.data.get("score")

        # 调取数据
        try:
            r = AllinpayRobotQiniuLog.objects.get(id=reqsn)
        except BaseException as err:
            raise ValidationError("查询消费记录失败")
        else:
            if not r.model:
                raise ValidationError("未找到相关声音模型")
            if not r.answer == answer:
                raise ValidationError("只能本人参与")

        # 检测刷单
        s = AllinpayRobotModelsSales.objects.filter(reqsn=r.reqsn).count()
        if s:
            raise ValidationError("禁止刷单行为")

        # 保存数据
        data = {
            "mid": r.model,
            "scene": r.mode,
            "reqsn": r.reqsn,
            "pay": r.amoney,
            "answer": answer,
            "score": score,
            "current": timezone.now(),
        }
        t = AllinpayRobotModelsSales(**data)
        t.save()
        return Response({"rescode": 200, "resmsg": t.id})


class ModelAllinpayRobotModelsSalesViewSet(viewsets.ModelViewSet):
    __title__ = "订阅模板评分"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询订阅模板评分列表",
        "post": "创建LOL配置基本",
        "put": "订阅模板评分",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>订阅模板评分列表</h4>
    retrieve:
    <h4>订阅模板评分详情</h4>
    create:
    <h4>创建LOL配置基本</h4>
    update:
    <h4>订阅模板评分</h4>
        {id} 订阅模板使用记录ID
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = [
        "get",
    ]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    # serializer_class = AllinpayRobotModelsSalesSerializer
    serializer_class = ModelAllinpayRobotModelsSalesSerializer
    queryset = AllinpayRobotModelsSales.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["mid", "scene", "answer"]
    search_fields = ["reqsn"]
    ordering_fields = "id"

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


# ================================================================================
#
# ================================================================================
class NewRebotAudioPostViewSet(viewsets.ModelViewSet):
    __title__ = "AI音频合成任务"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "创建AI音频合成任务",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>创建AI音频合成任务</h4>
        调用21#接口获取结果
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = NewRebotAudioPostSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.data.copy()

        # try:  # 加载好友信息
        #     r = AllinpayRobotList.objects.get(id=data.get("user"), isbot__gt=0)
        # except BaseException as err:
        #     raise ValidationError("加载好友信息失败")

        try:  # 加载模型信息
            r = AllinpayRobotConfig.objects.get(id=data.get("user"), status=1)
        except BaseException as err:
            raise ValidationError(f"加载模型信息失败: {err}")

        # 创建任务
        guid = str(uuid.uuid1())
        reqsn = f'VP{time.strftime("%Y%m%d%H%M%S", time.localtime())}{has_chocode(6)}'
        task = AllinpayRobotQiniuLog(
            **{
                "reqsn": reqsn,
                "guid": guid,
                "mode": "Audio",
                "answer": answer,
                "model": r.id,
                "chat": data.get("chat"),
                "language": data.get("language"),
                "status": 0,
                "current": timezone.now(),
                "description": "文转声",
            }
        )
        task.save()
        try:  # 扣费
            TASKS.task_Consumption(**{"task_id": task.id})
        except BaseException as err:
            raise ValidationError(f"扣费失败: {err}")
        # 任务调度
        res = TASKS.tasks_Manager.delay(**{"task_id": task.id})

        # 返回任务
        return Response({"rescode": 200, "resmsg": guid, "task": res.task_id})


class NewRebotVideoPostViewSet(viewsets.ModelViewSet):
    __title__ = "AI视频合成任务"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "创建AI视频合成任务",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>创建AI视频合成任务</h4>
        调用21#接口获取结果
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = NewRebotVideoPostSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 验证特权密码
        # try:
        #     pswd = serializer.data.get("pswd")
        #     AllinpayUserVerify.objects.get(id=answer, password=pswd)
        # except BaseException as err:
        #     print(err)
        #     raise ValidationError("特权密码校验失败")
        # 判断余额
        sell = TASKS.balance_from_userai("Video")
        guota = sell[0]
        args = TASKS.balance_from_userid(answer)
        if args[0] < guota:
            raise ValidationError("账户余额不足")
        # 创建扣费
        reqsn = f'VP{time.strftime("%Y%m%d%H%M%S", time.localtime())}{has_chocode(6)}'
        pay = TASKS.User_account_deduction(
            **{
                "reqsn": reqsn,
                "description": sell[1],
                "amoney": sell[0],
                "atotal": 0,
                "userid": answer,
                "dbid": settings.ROBOT_MONEY_DEFAULT,
                "current": timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
            }
        )
        if not pay == "success":
            raise ValidationError("支付失败")
        # 创建任务
        szer = AllinpayRobotQiniuLogSerializer(data=serializer.data)
        szer.is_valid(raise_exception=True)
        szer.save(answer=answer, mode="Video", reqsn=reqsn, amoney=sell[0])

        # 云任务
        r = TASKS.MakeSoundTasks.delay(**{"task_id": szer.data["id"]})
        # # 任务缓存
        # rds = get_redis_connection("sysconf")
        # rds.rpush(
        #     "video",
        #     szer.data["id"],
        # )
        # count = rds.llen("video")
        # 返回任务
        return Response({"rescode": 200, "resmsg": szer.data["guid"], "count": 0})


class NewRebotVideoDirectViewSet(viewsets.ModelViewSet):
    __title__ = "直达:AI视频合成任务"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "创建AI视频合成任务",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>创建AI视频合成任务</h4>
        调用21#接口获取结果
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = NewRebotVideoDirectSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 格式化数据
        mode = "Video"
        guid = str(uuid.uuid1())
        data = serializer.data.copy()

        # 查询模型
        try:
            model = AllinpayRobotConfig.objects.get(id=data["model"], status=1)
        except BaseException as err:
            raise ValidationError("模型不可用")

        # 获取增值
        if model.answer == answer:
            added = 0
        else:
            try:
                share = AllinpayRobotConfigShare.objects.get(
                    id=serializer.data.get("user")
                )
            except BaseException as err:
                raise ValidationError("模型没有共享")
            else:
                added = share.audio

        # 判断余额
        sell = TASKS.balance_from_userai(mode)
        guota = sell[0] + added
        args = TASKS.balance_from_userid(answer)
        if args[0] < guota:
            raise ValidationError(f"账户余额不足")

        # 创建扣费
        reqsn = f'VP{time.strftime("%Y%m%d%H%M%S", time.localtime())}{has_chocode(6)}'
        sell = TASKS.balance_from_userai(mode)
        pay = TASKS.User_account_deduction(
            **{
                "reqsn": reqsn,
                "description": sell[1],
                "amoney": guota,
                "atotal": 0,
                "userid": answer,
                "dbid": settings.ROBOT_MONEY_DEFAULT,
                "current": timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
            }
        )
        if not pay == "success":
            raise ValidationError(f"支付失败")

        # 创建入账
        if added > 0:
            licre = 0 - math.ceil(added * settings.RPBOT_MONEY_SHARE / 100)
            repay = TASKS.User_account_deduction(
                **{
                    "reqsn": f"{reqsn}A",
                    "description": sell[1] + ", 模型返点",
                    "amoney": licre,
                    "atotal": 0,
                    "userid": model.answer,
                    "dbid": settings.ROBOT_MONEY_DEFAULT,
                    "current": timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
                }
            )
            if not repay == "success":
                pass

        # 创建任务
        szer = AllinpayRobotQiniuLogSerializer(
            data={
                "guid": guid,
                "answer": answer,
                "mode": mode,
                "reqsn": reqsn,
                "amoney": sell[0],
                "model": model.id,
                "chat": data["chat"],
                "language": data["language"],
                "image": data["image"],
            }
        )
        szer.is_valid(raise_exception=True)
        szer.save()

        # 云任务
        r = TASKS.MakeSoundTasks.delay(**{"task_id": szer.data["id"]})
        # 任务缓存
        # rds = TASKS.get_redis_connection("sysconf")
        # rds.rpush(
        #     "audio",
        #     szer.data["id"],
        # )
        # count = rds.llen("audio")

        # 返回任务ID
        return Response(
            {
                "rescode": 200,
                "resmsg": guid,
                "count": 0,
                "description": "调用#21 或者 #64接口获取结果",
            }
        )


class AllinpayRobotQiniuLogViewSet(viewsets.ModelViewSet):
    __title__ = "任务历史记录"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询任务历史记录列表",
        "post": "创建LOL配置基本",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>任务历史记录列表</h4>
        "mode":任务类型 "Text ", "Audio 文本合成音频", "Video 音频合成视频", "content", "Voice 订阅音频", "Mpeg 订阅视频"
        "guid":任务ID
        "answer": 用户ID
        "status": 任务完成状态
        "model": 角色ID
        "mate": 好友ID
        "sell": 推荐
    retrieve:
    <h4>任务历史记录详情</h4>
    create:
    <h4>创建LOL配置基本</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["get"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotQiniuLogSerializer
    queryset = AllinpayRobotQiniuLog.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    filterset_class = AllinpayRobotQiniuLogFilterSet
    # filterset_fields = ["mode", "guid", "answer", "status", "model", "mate", "sell"]
    search_fields = ["reqsn", "guid"]
    ordering_fields = ["id", "-id"]

    pagination_class = StandardPagination

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayRobotSyncPostViewSet(viewsets.ModelViewSet):
    __title__ = "lipsync唇动接口"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "lipsync唇动接口",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>lipsync唇动接口</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotSyncPostSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.data.copy()

        # 创建任务
        guid = str(uuid.uuid1())
        reqsn = f'VP{time.strftime("%Y%m%d%H%M%S", time.localtime())}{has_chocode(6)}'
        task = AllinpayRobotQiniuLog(
            **{
                "reqsn": reqsn,
                "guid": guid,
                "mode": "Lipsync",
                "answer": answer,
                "audio": data["audio"],
                "video": data["video"],
                "status": 0,
                "current": timezone.now(),
                "description": "Lipsync合成",
            }
        )
        task.save()
        try:  # 扣费
            TASKS.task_Consumption(**{"task_id": task.id})
        except BaseException as err:
            raise ValidationError(err)
        # 任务调度
        res = TASKS.tasks_Manager.delay(**{"task_id": task.id})
        return Response(
            {
                "rescode": 200,
                "resmsg": guid,
                "task": res.task_id,
                "description": "调用#21 或者 #64接口获取结果",
            }
        )


class AllinpayRobotSyncDirectViewSet(viewsets.ModelViewSet):
    __title__ = "直达:lipsync唇动接口"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "lipsync唇动接口",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>lipsync唇动接口</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotSyncDirectSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.data.copy()

        # 查询模型
        try:
            model = AllinpayRobotConfig.objects.get(id=data["model"])
        except BaseException as err:
            raise ValidationError("加载模型失败")
        # 创建任务
        guid = str(uuid.uuid1())
        reqsn = f'VP{time.strftime("%Y%m%d%H%M%S", time.localtime())}{has_chocode(6)}'
        task = AllinpayRobotQiniuLog(
            **{
                "reqsn": reqsn,
                "guid": guid,
                "mode": "Lipsync",
                "answer": answer,
                "model": model.id,
                "chat": data["chat"],
                "language": data["language"],
                "video": data["video"],
                "status": 0,
                "current": timezone.now(),
                "description": "Lipsync合成",
            }
        )
        task.save()
        try:  # 扣费
            TASKS.task_Consumption(**{"task_id": task.id})
        except BaseException as err:
            raise ValidationError(err)
        # 任务调度
        res = TASKS.tasks_Manager.delay(**{"task_id": task.id})
        # 返回任务ID
        return Response(
            {
                "rescode": 200,
                "resmsg": guid,
                "task": res.task_id,
                "description": "调用#21 或者 #64接口获取结果",
            }
        )


class AllinpayRobotOpencvPostViewSet(viewsets.ModelViewSet):
    __title__ = "单图加音频转视频"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "图转视频",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>单图加音频转视频</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotOpencvPostSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.data.copy()
        # 创建任务
        guid = str(uuid.uuid1())
        reqsn = f'VP{time.strftime("%Y%m%d%H%M%S", time.localtime())}{has_chocode(6)}'
        task = AllinpayRobotQiniuLog(
            **{
                "reqsn": reqsn,
                "guid": guid,
                "mode": "Opencv",
                "answer": answer,
                "image": data["image"],
                "audio": data["audio"],
                "status": 0,
                "current": timezone.now(),
                "description": "单图合成视频",
            }
        )
        task.save()
        try:  # 扣费
            TASKS.task_Consumption(**{"task_id": task.id})
        except BaseException as err:
            raise ValidationError(err)
        # 任务调度
        res = TASKS.tasks_Manager.delay(**{"task_id": task.id})
        return Response(
            {
                "rescode": 200,
                "resmsg": guid,
                "task": res.task_id,
                "description": "调用#21 或者 #64接口获取结果",
            }
        )


class AllinpayRobotOpencvDirectViewSet(viewsets.ModelViewSet):
    __title__ = "直达:单图加音频转视频"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询LOL配置基本列表",
        "post": "图转视频",
        "put": "编辑LOL配置基本",
        "patch": "编辑LOL配置基本",
        "delete": "移除LOL配置基本",
    }
    __doc__ = """	
    list:
    <h4>LOL配置基本列表</h4>
    retrieve:
    <h4>LOL配置基本详情</h4>
    create:
    <h4>单图加音频转视频</h4>
    update:
    <h4>编辑LOL配置基本</h4>
    partial_update:
    <h4>编辑LOL机位系数</h4>
    delete:
    <h4>移除LOL配置基本</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotOpencvDirectSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.data.copy()

        # 查询模型
        try:
            model = AllinpayRobotConfig.objects.get(id=data["model"])
        except BaseException as err:
            raise ValidationError("加载模型失败")
        # 创建任务
        guid = str(uuid.uuid1())
        reqsn = f'VP{time.strftime("%Y%m%d%H%M%S", time.localtime())}{has_chocode(6)}'
        task = AllinpayRobotQiniuLog(
            **{
                "reqsn": reqsn,
                "guid": guid,
                "mode": "Opencv",
                "answer": answer,
                "model": model.id,
                "chat": data["chat"],
                "language": data["language"],
                "image": data["image"],
                "status": 0,
                "current": timezone.now(),
                "description": "单图合成视频",
            }
        )
        task.save()
        try:  # 扣费
            TASKS.task_Consumption(**{"task_id": task.id})
        except BaseException as err:
            raise ValidationError(err)
        # 任务调度
        res = TASKS.tasks_Manager.delay(**{"task_id": task.id})
        # 返回任务ID
        return Response(
            {
                "rescode": 200,
                "resmsg": guid,
                "task": res.task_id,
                "description": "调用#21 或者 #64接口获取结果",
            }
        )


class AllinpayRobotListmyShareViewSet(viewsets.ModelViewSet):
    __title__ = "我的公共好友"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询我的公共好友列表",
        "post": "创建我的公共好友",
        "put": "编辑我的公共好友",
        "patch": "编辑我的公共好友",
        "delete": "移除我的公共好友",
    }
    __doc__ = """
    list:
    <h4>我的公共好友列表</h4>
    retrieve:
    <h4>我的公共好友详情</h4>
    create:
    <h4>创建我的公共好友</h4>
    update:
    <h4>编辑我的公共好友</h4>
    partial_update:
    <h4>编辑我的公共好友</h4>
    delete:
    <h4>移除我的公共好友</h4>"""
    http_method_names = ["get", "put", "delete"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotListmyShareSerializer
    queryset = AllinpayRobotListmyShare.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["vid", "status", "isbot"]
    search_fields = ["nicename", "linkforme"]
    ordering_fields = "id"

    pagination_class = StandardPagination

    def list(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        queryset = self.filter_queryset(self.get_queryset().filter(answer=answer))
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        instance = self.get_object()
        if not instance.answer == answer:
            raise ValidationError("没有权限")
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=answer, current=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        partial = False
        instance = self.get_object()
        if not instance.answer == answer:
            raise ValidationError("没有权限")
        data = {
            "nicename": request.data["nicename"],
            "linkforme": request.data["linkforme"],
        }
        instance.nicename = request.data["nicename"]
        instance.linkforme = request.data["linkforme"]
        instance.lasttime = timezone.now()
        instance.save()
        serializer = self.get_serializer(instance)
        # serializer.is_valid(raise_exception=True)
        # serializer.save(lasttime=timezone.now())

        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        instance = self.get_object()
        if not instance.answer == answer:
            raise ValidationError("没有权限")
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayRobotListmySharePostViewSet(viewsets.ModelViewSet):
    __title__ = "创建我的公共好友"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI爱好标签列表",
        "post": "创建我的公共好友",
        "put": "编辑AI爱好标签",
        "patch": "编辑AI爱好标签",
        "delete": "移除AI爱好标签",
    }
    __doc__ = """
    list:
    <h4>AI爱好标签列表</h4>
    retrieve:
    <h4>AI爱好标签详情</h4>
    create:
    <h4>创建我的公共好友</h4>
    update:
    <h4>编辑AI爱好标签</h4>
    partial_update:
    <h4>编辑AI爱好标签</h4>
    delete:
    <h4>移除AI爱好标签</h4>"""
    http_method_names = ["post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotListmySharePostSerializer
    queryset = AllinpayRobotListmyShare.objects.all()

    def create(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 基础数据
        ssid = serializer.data.get("vid")
        pswd = serializer.data.get("pswd")
        nicename = serializer.data.get("nicename")
        linkforme = serializer.data.get("linkforme")
        # 验证好友
        if AllinpayRobotListmyShare.objects.filter(vid=ssid, answer=answer).count():
            raise ValidationError("该好友已经添加")

        # 好友数据
        try:
            r = AllinpayRobotList.objects.get(id=ssid, isbot__gt=0, share__gt=0)
        except BaseException as err:
            raise ValidationError("查询共享的虚拟好友失败")
        if not r.share:
            raise ValidationError("该好友不允许添加")
        if r.share == 1 or (r.share == 2 and r.auth == pswd):
            data = {
                "vid": r.id,
                "isbot": r.isbot,
                "answer": answer,
                "status": 1,
                "nicename": nicename,
                "linkforme": linkforme,
                "current": timezone.now(),
                "parent": r.parent,
            }
        elif r.share == 3:
            data = {
                "vid": r.id,
                "isbot": r.isbot,
                "answer": answer,
                "status": 0,
                "nicename": nicename,
                "linkforme": linkforme,
                "current": timezone.now(),
                "parent": r.parent,
            }
        else:
            raise ValidationError("创建失败: 验证消息错误或好友未开放共享")
        try:
            s = AllinpayRobotListmyShare(**data)
            s.save()
            # # 克隆好友
            # if s.status == 1:
            #     TASKS.clone_Share_friend.delay(**{"share": s.id})
        except BaseException as err:
            raise ValidationError(f"创建失败:{err}")
        return Response(
            {"rescode": 200, "resmsg": AllinpayRobotListmyShareSerializer(s).data}
        )


class AllinpayRobotListmyShareListViewSet(viewsets.ModelViewSet):
    __title__ = "我的好友请求"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询我的好友请求列表",
        "post": "创建AI爱好标签",
        "put": "编辑AI爱好标签",
        "patch": "编辑AI爱好标签",
        "delete": "同意好友请求",
    }
    __doc__ = """
    list:
    <h4>我的好友请求列表</h4>
    retrieve:
    <h4>同意好友请求</h4>
    create:
    <h4>创建AI爱好标签</h4>
    update:
    <h4>编辑AI爱好标签</h4>
    partial_update:
    <h4>编辑AI爱好标签</h4>
    delete:
    <h4>拒绝好友请求</h4>"""
    http_method_names = ["get", "delete"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayRobotListmyShareSerializer
    queryset = AllinpayRobotListmyShare.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["parent", "vid", "answer", "status"]
    search_fields = ["nicename", "linkforme"]
    ordering_fields = "id"

    pagination_class = StandardPagination

    def list(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        queryset = self.filter_queryset(
            self.get_queryset().filter(parent=answer, status=0)
        )
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        instance = self.get_object()
        if not instance.parent == answer:
            raise ValidationError("请求错误")
        if instance.status > 0:
            raise ValidationError("状态错误")
        # partial = False
        # serializer = self.get_serializer(instance, data={"status": 1}, partial=partial)
        # serializer.is_valid(raise_exception=True)
        # serializer.save(lasttime=timezone.now())
        instance.status = 1
        instance.lasttime = timezone.now()
        instance.save()
        return Response({"rescode": 200, "resmsg": "SUCCESS"})

    def destroy(self, request, *args, **kwargs):
        answer = request.user.id if request.user else 1
        instance = self.get_object()
        if not instance.parent == answer:
            raise ValidationError("请求权限错误")
        if instance.status > 0:
            raise ValidationError("请求状态错误")
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class DepositMoneyViewSet(viewsets.ModelViewSet):
    __title__ = "充值修正"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI爱好标签列表",
        "post": "充值修正",
        "put": "编辑AI爱好标签",
        "patch": "编辑AI爱好标签",
        "delete": "移除AI爱好标签",
    }
    __doc__ = """
    list:
    <h4>AI爱好标签列表</h4>
    retrieve:
    <h4>AI爱好标签详情</h4>
    create:
    <h4>充值修正</h4>
        管理员后台功能
    update:
    <h4>编辑AI爱好标签</h4>
    partial_update:
    <h4>编辑AI爱好标签</h4>
    delete:
    <h4>移除AI爱好标签</h4>"""
    http_method_names = ["post"]
    authentication_classes = [] if settings.DEBUG else [AdminJWTAuthentication]
    permission_classes = [AllPermissions] if settings.DEBUG else [AdminPermissions]
    serializer_class = DepositMoneySerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        from mysqldb.tasks import balance_from_userid, EncryptedData

        userid = serializer.data["userid"]
        money = serializer.data["bmoney"]
        args = balance_from_userid(userid)
        r = AllinpayRobotAccount(
            **{
                "reqsn": f'AI{time.strftime("%Y%m%d%H%M%S", time.localtime())}{has_chocode(6)}',
                "description": "管理员充值修正",
                "amoney": 0,
                "bmoney": money,
                "atotal": 0,
                "btotal": args[1],
                "current": timezone.now(),
                "hmoney": EncryptedData(money),
                "htotal": EncryptedData(args[1]),
                "userid": userid,
                "dbid": settings.ROBOT_MONEY_DEFAULT,
            }
        )
        r.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayWxchatSpreadViewSet(viewsets.ModelViewSet):
    __title__ = "小程序推广码"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询小程序推广码列表",
        "post": "创建小程序推广码",
        "put": "编辑AI爱好标签",
        "patch": "编辑AI爱好标签",
        "delete": "移除AI爱好标签",
    }
    __doc__ = """
    list:
    <h4>小程序推广码列表</h4>
    retrieve:
    <h4>小程序推广码详情</h4>
        该接口会补领二维码
    create:
    <h4>小程序推广码</h4>
    update:
    <h4>编辑AI爱好标签</h4>
    partial_update:
    <h4>编辑AI爱好标签</h4>
    delete:
    <h4>移除AI爱好标签</h4>"""
    http_method_names = ["get", "post"]
    authentication_classes = [UsersJWTAuthentication]
    permission_classes = [UserPermissions]
    serializer_class = AllinpayWxchatSpreadSerializer
    queryset = AllinpayWxchatSpread.objects.all()

    filter_backends = [MyFilterBackend, MySearchBackend, MyOrderBackend]
    # filterset_class = CallmeListFilterSet
    filterset_fields = ["answer", "name"]
    # search_fields = ['phone','email']
    ordering_fields = "id"

    pagination_class = StandardPagination

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        c = queryset.count()
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
                "count": c,
                "size": self.pagination_class.page_size,
            }
        )

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        if not instance.qrcode:  # .delay
            res = TASKS.MakeWxchatAppSpread(**{"id": instance.id})
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        res = serializer.data
        if not serializer.data.get("qrcode"):  # .delay
            res = TASKS.MakeWxchatAppSpread(**{"id": serializer.data["id"]})
        return Response({"rescode": 200, "resmsg": res})


class NewUserSpreadViewSet(viewsets.ModelViewSet):
    __title__ = "验证推广计划"
    __group__ = "AI好友模块"
    __info__ = {
        "get": "查询AI爱好标签列表",
        "post": "验证推广计划",
        "put": "编辑AI爱好标签",
        "patch": "编辑AI爱好标签",
        "delete": "移除AI爱好标签",
    }
    __doc__ = """
    list:
    <h4>AI爱好标签列表</h4>
    retrieve:
    <h4>AI爱好标签详情</h4>
    create:
    <h4>验证推广计划</h4>
    update:
    <h4>编辑AI爱好标签</h4>
    partial_update:
    <h4>编辑AI爱好标签</h4>
    delete:
    <h4>移除AI爱好标签</h4>"""
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = NewUserSpreadSerializer
    queryset = AllinpayWxchatList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # serializer.save()
        answer = serializer.data["answer"]
        openid = serializer.data["openid"]
        x = self.get_queryset().filter(Q(openid=openid) | Q(appid=openid)).count()
        if x > 0:
            raise BaseException("该用户非新用户")
        # 创建入账
        reqsn = f'PG{time.strftime("%Y%m%d%H%M%S", time.localtime())}{has_chocode(6)}'
        licre = 0 - settings.RPBOT_MONEY_SPREAD
        repay = TASKS.User_account_deduction(
            **{
                "reqsn": f"{reqsn}",
                "description": f"小程序推广计划奖励 {openid}",
                "amoney": licre,
                "atotal": 0,
                "userid": answer,
                "dbid": settings.ROBOT_MONEY_DEFAULT,
                "current": timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
            }
        )
        if not repay == "success":
            raise BaseException("奖励失败")
        # RPBOT_MONEY_SPREAD
        return Response({"rescode": 200, "resmsg": settings.RPBOT_MONEY_SPREAD})


# 检查视图
filter_views(globals())
